package smap;

import BD.UsuarioBD;
import ConexaoBackupBD.ConexaoBD;
import ConexaoBackupBD.ConfiguracaoBD;
import DAO.UsuarioDAO;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;

public class FormLogin extends javax.swing.JDialog {

    UsuarioDAO usuDao = new UsuarioDAO(); 
    Date dataDeHoje = new Date();
    SimpleDateFormat formato = new SimpleDateFormat();
    
    public FormLogin(java.awt.Frame parent, boolean modal) {      
        super(parent, modal);
        initComponents();
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblLogo = new javax.swing.JLabel();
        lblUsuario = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        lblSenha = new javax.swing.JLabel();
        txtSenha = new javax.swing.JPasswordField();
        jButton1 = new javax.swing.JButton();
        btnLogar = new javax.swing.JButton();
        btnConfigConexao = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Bem vindo ao SMAP");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setFont(new java.awt.Font("Comic Sans MS", 0, 12)); // NOI18N
        setLocationByPlatform(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        lblLogo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/smap2.gif"))); // NOI18N

        lblUsuario.setText("Usuário:");

        lblSenha.setText("Senha:");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Login-out-icon.png"))); // NOI18N
        jButton1.setText("Sair");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        btnLogar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Login-in-icon.png"))); // NOI18N
        btnLogar.setText("Logar");
        btnLogar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLogarActionPerformed(evt);
            }
        });

        btnConfigConexao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/configurar-icon.png"))); // NOI18N
        btnConfigConexao.setText("Configurar conexão");
        btnConfigConexao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfigConexaoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(lblLogo)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(6, 6, 6)
                                .addComponent(lblSenha))
                            .addComponent(lblUsuario, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtSenha)
                            .addComponent(txtUsuario)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnConfigConexao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnLogar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblUsuario)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblSenha)
                    .addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(btnLogar)
                    .addComponent(btnConfigConexao))
                .addGap(0, 0, Short.MAX_VALUE))
            .addComponent(lblLogo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>//GEN-END:initComponents

    private void btnLogarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLogarActionPerformed
        if(verificarArquivo()){ //verifica se existe o arquivo config.txt. Se não existe pede para criar.
            if(testarConexao()){ //testa conexão com os dados lidos do arquivo. Se ok, prossegue, se conter erro pede pra reconfigurar.
                //seta os dados do usuario para verificar login
                UsuarioBD usu = new UsuarioBD();
                usu.setNome(txtUsuario.getText().trim().toString());
                usu.setSenha(new String(txtSenha.getPassword()));

                if(usuDao.logar(usu)){
                    this.dispose();
                    TelaPrincipal tp = new TelaPrincipal();
                    //tp.TabelaAtividades(formato.format(dataDeHoje));
                    //tp.TabelaAvisos();
                    tp.setVisible(true);  
                }else{
                    JOptionPane.showMessageDialog(null,"Usuário e/ou senha inválido(s)", 
                    "Erro ao logar no sistema", JOptionPane.ERROR_MESSAGE);         
                }                 
            }else{
                TelaConfiguracaoBD config = new TelaConfiguracaoBD(null, true);
                config.setarDadosConexao();
                config.setVisible(true);
            }           
        }
    }//GEN-LAST:event_btnLogarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnConfigConexaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfigConexaoActionPerformed
        TelaConfiguracaoBD telcon = new TelaConfiguracaoBD(null, true);
        telcon.setarDadosConexao(); //se houver algo já cadastrado
        telcon.setVisible(true);
    }//GEN-LAST:event_btnConfigConexaoActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        verificarArquivo();
    }//GEN-LAST:event_formWindowOpened

     /**Verifica se já existe arquivo de configuração. Se não houver
      * abre a tela de configuração.
      */
    public boolean verificarArquivo(){
        ConfiguracaoBD conf = new ConfiguracaoBD();
        boolean resposta = conf.verificarArquivo();
        if(resposta){ //se arquivo já existe
            conf.lerArquivo(); //carrega a string de conexão
            return true;
        }
        else{ // não existe arquivo config.txt, necessário configurar
            JOptionPane.showMessageDialog(null,"Este é o seu primeiro acesso ao SMAP,"
                    + "ou o arquivo de conexão foi deletado. Por favor configure as "
                    + "informações quanto ao banco de dados.", 
             "Configurar banco de dados", JOptionPane.INFORMATION_MESSAGE);
            TelaConfiguracaoBD tconfig = new TelaConfiguracaoBD(null, true);
            tconfig.setVisible(true);
            return false;
        }
    }
    
    public boolean testarConexao(){
        //testar se a conexão é valida para as configurações setadas no arquivo
        ConexaoBD con = new ConexaoBD();
        boolean resultado = con.testarConexao();
        return resultado;
    }

    public static void main(String args[]) {

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                FormLogin dialog = new FormLogin(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConfigConexao;
    private javax.swing.JButton btnLogar;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel lblLogo;
    private javax.swing.JLabel lblSenha;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JPasswordField txtSenha;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables

    
}
